/**
 * Created by c.y on 2018/3/16.
 * Updated by 汤彦祖 on 2018/4/11
 * 采用axios发送请求，这是对请求的全局处理
 * 在获取数据时应当防止用户操作，打开loding
 */
import Vue from 'vue';
import {AjaxPlugin, md5} from 'vux';
import sign from '../tool/loginSign';
import store from '../store/index';

Vue.use(AjaxPlugin);

// 创建实例
const Service = Vue.http.create({
    timeout: 1000 * 6, // 6秒超时
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
    transformRequest: [function (data) {
        if (data === undefined) {
            return data
        }
        // 参数转换处理
        let ret = '';
        for (let it in data) {
            if (data[it] == null) {
                data[it] = '';
            }
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
    }]
});

// 全局拦截器设置
Service.interceptors.request.use(config => {
    
    // Do something before request is sent
    //  ================begin ===================
    
    store.commit('UPDATE_LOADING', {isLoading: true});
    
    // 验签 用于所有没有登录并传递有电话号码的接口验签
    
    //  ================end   ===================
    return config;
}, (error) => {
    store.commit('UPDATE_LOADING', {isLoading: false});
    return Promise.reject(error);
});

// response统一处理操作
Service.interceptors.response.use(res => {
    store.commit('UPDATE_LOADING', {isLoading: false});
    return res.data;
}, (error) => {
    store.commit('UPDATE_LOADING', {isLoading: false});
    return Promise.reject(error);
});

export default Service;
